import saleOrdersAPI from '../../../common/api/breedsales/orderbills.api.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../../common/api/file-request.js';
import doT from '../../../../vendor/template/doT.js';
import { requestDict, DictionaryType } from '../../../common/dictionary/dictionary-type.js';
import { multiplicationFixed, division, subtractBig, additionBig, multiplicationBig, divisionBig } from '../../../common/accuracy-calculation/index.js';
import { Select2Page } from '../../../common/serve-request.js';

(function (window, document, $) {
    let _vm,
        getWeighInfo = [],
        _salespricings = {},
        checkEmploy = [],
        earNumsList = [],
        checkboxList = [],
        breedDeliveEntry = [],
        _pigTypeList = [],
        _speLevelList = [],
        checkEmployTms = [],
        earNumsListTms = [],
        checkboxListTms = [];
    const _json = Utils.ParsingUrl(window.location);
    const weightTemplate = doT.template($('#weight-template').text());
    const BaseCfgUrl = Utils.CurDomain.BaseCfgUrl;
    let _page = {
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    };
    $(async function () {
        _vm = new Vue({
            el: '#addsaleorders-form',
            data() {
                return {
                    orderId: '',
                    seq: 0,
                    weight: 0,
                    count: 0,
                    attaches: '',
                    uploadCount: 0,
                    images: [], ///处理weui自带上传插件回显重新上传时的问题
                    page: { ..._page },
                    checkEmploy: '',
                    earNumsList: '',
                    checkboxList: '',
                    checkEmployTms: '',
                    earNumsListTms: '',
                    checkboxListTms: '',
                };
            },
            methods: {
                submit() {
                    savedata();
                },
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        await _initCommand();
        uploadInit();
        _initPigInfo();
        _initTmsInfo();
    });

    //命令初始化
    const _initCommand = async () => {
        //销售品类
        requestDict(DictionaryType.LEVEL_TYPE).then((res) => {
            _speLevelList = res.data;
        });

        await requestDict(DictionaryType.PIG_FIXEDPRICE_TYPE).then((res) => {
            _pigTypeList = res.data;
        });
        //查询销售定价表信息
        // _salespricings = await saleOrdersAPI.getSalesPricings();
        getWeighInfo = JSON.parse(Utils.GetSessionStorage('getWeighInfo'));
        $('#weightorders').empty().append(weightTemplate(getWeighInfo));

        if (Utils.IsNotNull(_json.count)) {
            $('#count').val(_json.count);
            $('#weight').val(_json.weight);

            if (Utils.IsNotNull(_json.attaches)) {
                _images(_json.attaches);
            }
        }
        // 种猪耳号
        // let allPigNum = await saleOrdersAPI.getPrmtSettings('PIGNUMCODE')
        // let allPigNumcode = JSON.parse(allPigNum)
        $('#pigEarDiv,#saleParityDiv').css('display', 'none');
        // 显示耳号选择框
        if (_json.pigType != 3 && _json.pigType != 4) {
            $('#pigEarDiv').css('display', 'block');
        }
        // 显示胎次
        if (_json.pigType == 2 || _json.pigType == 6) {
            $('#saleParityDiv').css('display', 'block');
        }
        // 过磅 计算净重
        $('#grossWeight,#tareWeight').on('change', function () {
            let grossWeight = $('#grossWeight').val();
            let tareWeight = $('#tareWeight').val();
            let netWeight = Number(grossWeight) - Number(tareWeight);
            $('#weight').val(netWeight);
        });
        $('#deliverRemark').val('');

        // 获取详情
        let thisRow = getWeighInfo[0];
        console.log(thisRow);

        // 初始化过磅数据源
        let allMaterial = await saleOrdersAPI.postMaterial();
        let allMaterialInfo = allMaterial.items.filter((item) => item.numCode.substring(0, 2) == '14');
        $(`#materialId`).select2({
            placeholder: '请选择物料...', //默认文字提示
            language: 'zh-CN', //汉化
            data: allMaterialInfo.map((item) => {
                return {
                    id: item.id,
                    text: `${item.name}(${item.numCode})`,
                    ...item,
                };
            }),
        });

        Select2Page(
            $(`#breedBatchId`),
            `${BaseCfgUrl}/breedbatchs/rlist`,
            (params) => {
                return JSON.stringify({
                    farmOrgName: '',
                    tags: '',
                    name: params.term,
                    sort: '',
                    isEnd: false,
                    farmOrgId: thisRow.farmOrgId,
                    pageSize: 20,
                    pageIndex: (params.page || 1) - 1,
                });
            },
            'POST',
            {
                placeholder: '请选择养殖批次...', //默认文字提示
                templateResult: function (res) {
                    return `${res.name}`;
                },
            },
        );
        // 选择养殖批次
        $('#breedBatchId').on('select2:select', function () {
            $(`#breedBatchName`).val($(this).select2('data')[0].name);
        });
        // 选择物料
        $('#materialId').on('select2:select', function () {
            $(`#materialName`).val($(this).select2('data')[0].name);
            $(`#materialNumCode`).val($(this).select2('data')[0].numCode);
            $(`#baseMeasureUnit`).val($(this).select2('data')[0].baseMeasureUnit);
            $(`#subMeasureUnit`).val($(this).select2('data')[0].subMeasureUnit);
        });

        $(`#specLevel`).select2({
            placeholder: '请选择销售品类...', //默认文字提示
            language: 'zh-CN', //汉化
            data: _speLevelList.map((item) => {
                return {
                    id: item.value,
                    text: item.displayName,
                };
            }),
        });
        let pricMesuUnit = [
            { id: 'TOU', text: 'TOU' },
            { id: 'KG', text: 'KG' },
        ];
        $(`#baseMeasureUnit`).select2({
            placeholder: '销售单位...', //默认文字提示
            language: 'zh-CN', //汉化
            data: pricMesuUnit,
        });

        $(`#breedBatchId`).setSelectValue(thisRow.breedBatchId, thisRow.breedBatchName);
        $(`#breedBatchName`).val(thisRow.breedBatchName);
        $(`#materialId`).setSelectValue(thisRow.materialId, thisRow.materialName);
        $(`#materialName`).val(thisRow.materialName);
        $(`#materialNumCode`).val(thisRow.materialNumCode);
        $(`#subMeasureUnit`).val(thisRow.subMeasureUnit);
        $(`#baseMeasureUnit`).setSelectValue(thisRow.baseMeasureUnit);
        $(`#specLevel`).setSelectValue(thisRow.specLevelId);
        $('#carNo').val(thisRow.carNo);
        $('#billNo').val(thisRow.billNo);

        if (Utils.IsNotNull(thisRow.planOrderId)) {
            $('#carNoDiv').css('display', 'block');
            $('#carNoDivHide').css('display', 'none');
        } else {
            $('#carNoDiv').css('display', 'none');
            $('#carNoDivHide').css('display', 'block');
        }
        // 收发货地址
        $('#sadress').val(thisRow?.receiveAddress);
        $('#radress').val(thisRow?.detailDeliveryAddress);
        //获取销售出库的信息 回写
        if (Utils.IsNotNull(getWeighInfo[0]?.weight)) {
            let deliverbillsInfo = await saleOrdersAPI.getDeliverBills(_json.orderId);
            let deliverInfo = deliverbillsInfo?.entries.find((item) => item.seq == _json.seq);
            //  毛重、皮重
            $('#grossWeight').val(deliverInfo?.grossWeight);
            $('#tareWeight').val(deliverInfo?.tareWeight);
            $('#deliverRemark').val(deliverInfo?.remark);
            $('#waybillNo').val(deliverInfo?.waybillNo);
            // 耳号
            let breedPigInfo = [];
            deliverbillsInfo?.breedPigEntries.map((item) => {
                if (item.seq == _json.seq) breedPigInfo.push(item);
            });
            // breedDeliveEntry = [...breedPigInfo]
            breedPigInfo.map((item) => (item.id = item.pigId));
            checkEmploy = [...breedPigInfo];
            checkboxList = checkEmploy.map((item) => item.pigId);
            if (Utils.IsNotNull(checkEmploy.length)) {
                $('#choose').html(`<span style = "margin-right: 24px;"> 已选择: ${checkEmploy.length} 个</span > `);
            }
            if (_json.pigType == 2 || _json.pigType == 6) {
                $(`#saleParity`).val(breedPigInfo[0]?.parity);
            }
        }

        //提交
        $('#informationSubmit').on('click', async function () {
            breedDeliveEntry = [];
            //保留两位小数
            const FLOAT_Method = /^[0-9]+(\.\d{1,2})?$/;
            if (!Utils.IsNotNull($(`#breedBatchId`).val())) {
                return $.toptip(`养殖批次不能为空!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#materialId`).val())) {
                return $.toptip(`物料不能为空!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#specLevel`).val())) {
                return $.toptip(`销售品类不能为空!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#baseMeasureUnit`).val())) {
                return $.toptip(`销售单位不能为空!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#carNo`).val()) && !Utils.IsNotNull($(`#carNoText`).val())) {
                return $.toptip(`运输车牌不能为空!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#weight`).val())) {
                return $.toptip(`净重不能为空!`, 'warning');
            }
            if (Number($('#weight').val()) == 0 || !FLOAT_Method.test($('#weight').val())) {
                return $.toptip(`净重必须大于0且小数点后最多为两位!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#grossWeight`).val())) {
                return $.toptip(`毛重不能为空!`, 'warning');
            }
            if (Number($('#grossWeight').val()) == 0 || !FLOAT_Method.test($('#grossWeight').val())) {
                return $.toptip(`毛重必须大于0且小数点后最多为两位!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#tareWeight`).val())) {
                return $.toptip(`皮重不能为空!`, 'warning');
            }
            if (!FLOAT_Method.test($('#tareWeight').val())) {
                return $.toptip(`皮重必须大于等于0且小数点后最多为两位!`, 'warning');
            }
            if (!Utils.IsNotNull($(`#count`).val())) {
                return $.toptip(`数量不能为空!`, 'warning');
            }
            if (!/(^[1-9]\d*$)/.test($('#count').val())) {
                return $.toptip(`数量必须大于0!`, 'warning');
            }

            checkEmploy.map((item) => {
                breedDeliveEntry.push({
                    seq: _json.seq,
                    pigId: item.id,
                    earNum: item.earNum,
                    earTag: item.earTag,
                    pigStatus: item.pigStatus,
                    parity: item.parity,
                    line: item.line,
                });
            });
            breedDeliveEntry.forEach((item, index) => (item.seqNum = index + 1));
            let _attaches = [],
                _entriesInfo = [];
            $.each(_vm.images, function (i, v) {
                _attaches.push(v.imageId);
            });
            let params = {
                orderId: _json.orderId,
                seq: _json.seq,
                tareWeight: Number($(`#tareWeight`).val()),
                grossWeight: Number($(`#grossWeight`).val()),
                weight: $('#weight').val(),
                count: $('#count').val(),
                attaches: _attaches.join(','),
                breedDeliveEntry: [...breedDeliveEntry],
                remark: $('#deliverRemark').val(),
                subMeasuerCount: 0,
                specLevel: $(`#specLevel`).val(),
                breedBatchId: $(`#breedBatchId`).val(),
                breedBatchName: 'PZ-202709' || $(`#breedBatchName`).val(),
                materialId: $(`#materialId`).val(),
                materialName: $(`#materialName`).val(),
                materialNumCode: $(`#materialNumCode`).val(),
                baseMeasureUnit: $(`#baseMeasureUnit`).val(),
                subMeasureUnit: $(`#subMeasureUnit`).val(),
                carNo: $('#carNo').val() || $('#carNoText').text(),
                transferCarNo: $('#transferCarNo').text(),
                deiverName: $('#deiverName').text(),
                deiverPhone: $('#deiverPhone').text(),
                waybillNo: $('#waybillNo').val(),
                sadress: $('#sadress').val(),
                radress: $('#radress').val(),
            };
            if (_json.pigType != 3 && _json.pigType != 4 && !Utils.IsNotNull(breedDeliveEntry)) {
                return $.toptip(`请选择猪只耳号!`, 'warning');
            }
            if (getWeighInfo[0].isGift == 'false') {
                //非赠送调用接口
                // 查询定价
                let _weight = (params.weight / params.count).toFixed(2);
                let pigType = _json.pigType;
                let pigTypeName = _pigTypeList.find((s) => s.value == pigType)?.displayName || '';
                if (!Utils.IsNotNull(pigTypeName)) {
                    return $.toptip(`猪只类型不存在!`, 'warning');
                }
                let bizdateInfo = moment(getWeighInfo[0].bizDate).format('YYYY-MM-DD');
                // 获取定价信息
                let queryJson = {
                    saledate: bizdateInfo,
                    farmid: getWeighInfo[0].farmOrgId,
                    customerid: getWeighInfo[0].cstmId,
                };
                let _salespricingsList = await saleOrdersAPI.salesPricingsQuery(queryJson);
                let _salespricingsFilter = _salespricingsList.filter((item) => item.bizFormObj.billStatus == 3);
                // 判断日期、组织、种猪类型
                let filterInfo = _salespricingsFilter.filter((item) => moment(item.saleDate).format('YYYY-MM-DD') == bizdateInfo && item.farmId == getWeighInfo[0].farmOrgId && item.pigType == pigType);
                // 判断养殖批次、客户、物料
                let allentries = filterInfo.flatMap((item) => item.entries);
                let entreisfilterInfo = allentries.filter((item) => item.customerId == getWeighInfo[0].cstmId && item.breedBatchId == params.breedBatchId && item.materialId == params.materialId);
                // 判断AB票
                let deliveryArry = getWeighInfo[0].deliveryRegion.split('|');
                let shipArry = getWeighInfo[0].shipRegion.split('|');
                let delivery = deliveryArry[0].split(';')[0];
                let ship = shipArry[0].split(';')[0];
                let bTypefilterInfo = [],
                    tipInfo = '';
                if (delivery == ship) {
                    //地址相同选B票 bType=2，过滤出不等于1的
                    bTypefilterInfo = entreisfilterInfo.filter((item) => item.bType != 1);
                    tipInfo = '票据类型为B票';
                } else if (delivery != ship) {
                    bTypefilterInfo = entreisfilterInfo.filter((item) => item.bType != 2);
                    tipInfo = '票据类型为A票';
                }
                //提示
                if (!Utils.IsNotNull(filterInfo) || !Utils.IsNotNull(entreisfilterInfo) || !Utils.IsNotNull(bTypefilterInfo)) {
                    return $.toptip(
                        `暂无查询到日期为${bizdateInfo}，农场为${getWeighInfo[0].farmOrgName}，客户为${getWeighInfo[0].cstmName}，批次为${params.breedBatchName}，猪只类型为${pigTypeName}，物料为${params.materialName}，${tipInfo}，已审核的定价信息!`,
                        'warning',
                    );
                }
                let weightfilterInfo = [];
                // 判断均重
                if (pigType != 1 && pigType != 4) {
                    weightfilterInfo = bTypefilterInfo.filter((item) => _weight < item.weightHigh && _weight >= item.weightLow);
                    if (!Utils.IsNotNull(weightfilterInfo)) {
                        return $.toptip(`暂无查询到均重为${_weight}的定价信息!`, 'warning');
                    }
                }
                // if (weightfilterInfo.length > 1) {
                //     return $.toptip(`均重为${_weight}的定价信息存在多条!`, 'warning');
                // }
                // params["price"] = weightfilterInfo[0].price;

                // 判断是否是种猪和仔猪
                if (pigType == 1 || pigType == 4) {
                    // 判断均重
                    weightfilterInfo = bTypefilterInfo.filter((item) => _weight <= item.weightHigh && _weight > item.weightLow);
                    if (!Utils.IsNotNull(weightfilterInfo)) {
                        return $.toptip(`暂无查询到均重为${_weight}的定价信息!`, 'warning');
                    }

                    if (weightfilterInfo.length > 1) {
                        return $.toptip(`均重为${_weight}的定价信息存在多条!`, 'warning');
                    }
                    params['price'] = weightfilterInfo[0].price;
                    // 总价
                    if (params.baseMeasureUnit == 'KG') {
                        params['totalPrice'] = multiplicationFixed(weightfilterInfo[0].price, params.weight, 2);
                    } else {
                        params['totalPrice'] = multiplicationFixed(weightfilterInfo[0].price, params.count, 2);
                    }
                    // 过滤出范围小于等于 均重下限 的数据
                    let lowfilterInfo = bTypefilterInfo.filter((item) => item.weightHigh <= weightfilterInfo[0].weightLow && item.saleUnit == 'TOU' && item.weightHigh < _weight);
                    // 获取规定重量（KG）
                    let kgfilterInfo = bTypefilterInfo.filter((item) => item.weightHigh <= weightfilterInfo[0].weightLow && item.saleUnit == 'KG' && item.weightHigh < _weight);
                    // 存在
                    if (weightfilterInfo[0].saleUnit == 'KG' && Utils.IsNotNull(lowfilterInfo)) {
                        let touPrice = multiplicationBig(lowfilterInfo[0].price, params.count);
                        // let kgPrice = (_weight - lowfilterInfo[0].weightHigh) * weightfilterInfo[0].price * params.count
                        // 总重量
                        let allWeight = multiplicationBig(lowfilterInfo[0].weightHigh, params.count);
                        // 超出重量
                        let ccWeight = subtractBig(params.weight, allWeight);
                        let kgPrice = multiplicationBig(ccWeight, weightfilterInfo[0].price);
                        let totalPrice = additionBig(touPrice, kgPrice);
                        let avgPrice = divisionBig(totalPrice, params.count);
                        params['price'] = avgPrice.toFixed(3);
                        params['totalPrice'] = totalPrice.toFixed(2);
                    }
                    // 存在基础重量和规定重量
                    if (weightfilterInfo[0].saleUnit == 'KG' && Utils.IsNotNull(lowfilterInfo) && Utils.IsNotNull(kgfilterInfo)) {
                        // 按头价格
                        let touPrice = multiplicationBig(lowfilterInfo[0].price, params.count);

                        // 规定总重量
                        let gdWeight = multiplicationBig(kgfilterInfo[0].weightHigh, params.count);
                        // 规定重量  超出重量
                        let gdcceight = subtractBig(params.weight, gdWeight);
                        // 规定重量 按KG价格
                        let gdkgPrice = multiplicationBig(gdcceight, weightfilterInfo[0].price);

                        // 基础总重量
                        let allWeight = multiplicationBig(lowfilterInfo[0].weightHigh, params.count);
                        // 基础重量 超出重量
                        let ccWeight = subtractBig(gdWeight, allWeight);
                        // 基础重量 按KG价格
                        let kgPrice = multiplicationBig(ccWeight, kgfilterInfo[0].price);

                        // 总价
                        let totalPrice = additionBig(touPrice, gdkgPrice);
                        totalPrice = additionBig(totalPrice, kgPrice);
                        // 均价
                        let avgPrice = divisionBig(totalPrice, params.count);
                        params['price'] = avgPrice.toFixed(3);
                        params['totalPrice'] = totalPrice.toFixed(2);
                    }

                    // 不足称 过滤出范围大于等于 均重上限 的数据
                    let hightfilterInfo = bTypefilterInfo.filter((item) => item.weightLow >= weightfilterInfo[0].weightHigh && item.saleUnit == 'KG' && item.weightLow > _weight);
                    // 存在
                    if (weightfilterInfo[0].saleUnit == 'TOU' && Utils.IsNotNull(hightfilterInfo)) {
                        // 按头重量
                        let touPrice = multiplicationBig(weightfilterInfo[0].price, params.count);
                        // 扣减金额
                        // 总重量
                        let allWeight = multiplicationBig(weightfilterInfo[0].weightHigh, params.count);
                        // 不足重量
                        let ccWeight = subtractBig(allWeight, params.weight);
                        let kgPrice = multiplicationBig(ccWeight, hightfilterInfo[0].price);
                        let totalPrice = subtractBig(touPrice, kgPrice);
                        let avgPrice = divisionBig(totalPrice, params.count);
                        params['price'] = avgPrice.toFixed(3);
                        params['totalPrice'] = totalPrice.toFixed(2);
                    }
                }
                // 肥猪
                if (pigType == 3) {
                    if (weightfilterInfo.length > 1) {
                        return $.toptip(`均重为${_weight}的定价信息存在多条!`, 'warning');
                    }
                    params['price'] = weightfilterInfo[0].price;
                    if (params.baseMeasureUnit == 'KG') {
                        params['totalPrice'] = multiplicationFixed(weightfilterInfo[0].price, params.weight, 2);
                    } else {
                        params['totalPrice'] = multiplicationFixed(weightfilterInfo[0].price, params.count, 2);
                    }
                    // 获取基础重量（TOU）
                    let lowfilterInfo = bTypefilterInfo.filter((item) => item.weightHigh <= weightfilterInfo[0].weightLow && item.saleUnit == 'TOU' && item.weightHigh < _weight);
                    if (lowfilterInfo[0]?.weightLow == 0) {
                        // 存在单头单价
                        // let lowfilterInfo = bTypefilterInfo.filter((item) => item.saleUnit == 'TOU');
                        if (Utils.IsNotNull(lowfilterInfo)) {
                            //头数金额
                            let touPrice = multiplicationBig(lowfilterInfo[0].price, params.count);
                            // 重量金额
                            let allWeight = params['totalPrice'];
                            // 总金额
                            let totalPrice = additionBig(touPrice, allWeight);
                            // 平均金额
                            let avgPrice = divisionBig(totalPrice, params.weight);
                            params['price'] = avgPrice.toFixed(3);
                            params['totalPrice'] = totalPrice.toFixed(2);
                        }
                    } else {
                        // 肥猪定价方法3：超重、不足称
                        // 存在
                        if (weightfilterInfo[0].saleUnit == 'KG' && Utils.IsNotNull(lowfilterInfo)) {
                            // 按头价格
                            let touPrice = multiplicationBig(lowfilterInfo[0].price, params.count);
                            // 标准总重量
                            let allWeight = multiplicationBig(lowfilterInfo[0].weightHigh, params.count);
                            // 超出重量
                            let ccWeight = subtractBig(params.weight, allWeight);
                            // 按KG价格
                            let kgPrice = multiplicationBig(ccWeight, weightfilterInfo[0].price);
                            // 总价
                            let totalPrice = additionBig(touPrice, kgPrice);
                            // 均价
                            let avgPrice = divisionBig(totalPrice, params.count);
                            params['price'] = avgPrice.toFixed(3);
                            params['totalPrice'] = totalPrice.toFixed(2);
                        }

                        // 不足称 过滤出范围大于等于 均重上限 的数据
                        let hightfilterInfo = bTypefilterInfo.filter((item) => item.weightLow >= weightfilterInfo[0].weightHigh && item.saleUnit == 'KG' && item.weightLow > _weight);
                        // 存在
                        if (weightfilterInfo[0].saleUnit == 'TOU' && Utils.IsNotNull(hightfilterInfo)) {
                            // 按头价格
                            let touPrice = multiplicationBig(weightfilterInfo[0].price, params.count);
                            // 标准总重量
                            let allWeight = multiplicationBig(weightfilterInfo[0].weightHigh, params.count);
                            // 不足重量
                            let ccWeight = subtractBig(allWeight, params.weight);
                            // 按KG价格
                            let kgPrice = multiplicationBig(ccWeight, hightfilterInfo[0].price);
                            // 总价
                            let totalPrice = subtractBig(touPrice, kgPrice);
                            // 均价
                            let avgPrice = divisionBig(totalPrice, params.count);
                            params['price'] = avgPrice.toFixed(3);
                            params['totalPrice'] = totalPrice.toFixed(2);
                        }
                    }
                }

                // 判断是否是淘汰母猪、淘汰公猪
                if (pigType == 2 || pigType == 6) {
                    // 判断胎次是否都一致
                    let saleParityValue = $('#saleParity').val();
                    let parityFlag = breedDeliveEntry.find((item) => item.parity != saleParityValue);
                    if (Utils.IsNotNull(parityFlag)) {
                        $.toptip('胎次与选择猪只的胎次不一致!', 'warning');
                        return;
                    }
                    // 判断是否有胎次定价信息
                    let parityfilterInfo = weightfilterInfo.filter((item) => item.parity == saleParityValue);
                    if (!Utils.IsNotNull(parityfilterInfo)) {
                        return $.toptip(`暂无查询到胎次为${saleParityValue}的定价信息!`, 'warning');
                    }
                    // 判断胎次相同的是否有多条
                    if (parityfilterInfo.length > 1) {
                        return $.toptip(`胎次为${saleParityValue}，均重为${_weight}的定价信息存在多条`, 'warning');
                    }
                    params['price'] = parityfilterInfo[0].price;

                    if (params.baseMeasureUnit == 'KG') {
                        params['totalPrice'] = multiplicationFixed(parityfilterInfo[0].price, params.weight, 2);
                    } else {
                        params['totalPrice'] = multiplicationFixed(parityfilterInfo[0].price, params.count, 2);
                    }
                }

                // 妊娠母猪 校验周次是否一致
                if (pigType == 5) {
                    const promises = breedDeliveEntry.map((item) => {
                        return new Promise((resolve, reject) => {
                            setTimeout(async function () {
                                try {
                                    let firstbreed = await saleOrdersAPI.getBreedingRecs(item.pigId);
                                    item.firstbreed = firstbreed;
                                    item.weekCount = 0;
                                    if (Utils.IsNotNull(firstbreed)) {
                                        let dateBegin = new Date(moment(firstbreed).format('YYYY-MM-DD'));
                                        item.weekCount = _weeksCalculation(dateBegin);
                                    }
                                    resolve();
                                } catch (error) {
                                    reject();
                                }
                            }, 500);
                        });
                    });
                    // 等待周次校验完成后再执行后续操作
                    Promise.all(promises)
                        .then((results) => {
                            let firstweekCount = breedDeliveEntry[0].weekCount;
                            let flag = breedDeliveEntry.find((item) => item.weekCount != firstweekCount);

                            if (flag) {
                                return $.toptip(`请相同周次的耳号!`, 'warning');
                            } else {
                                // 判断周次相同的是否有多条
                                let weekfilterInfo = weightfilterInfo.filter((item) => item.weekCount == firstweekCount);
                                if (!Utils.IsNotNull(weekfilterInfo)) {
                                    return $.toptip(`暂未查询到周次为${firstweekCount}的数据`, 'warning');
                                }
                                if (weekfilterInfo.length > 1) {
                                    return $.toptip(`周次为${firstweekCount}，均重为${_weight}的定价信息存在多条`, 'warning');
                                }
                                params['price'] = weekfilterInfo[0].price;
                                if (params.baseMeasureUnit == 'KG') {
                                    params['totalPrice'] = multiplicationFixed(weekfilterInfo[0].price, params.weight, 2);
                                } else {
                                    params['totalPrice'] = multiplicationFixed(weekfilterInfo[0].price, params.count, 2);
                                }
                                // 调用接口完成订单
                                return saleOrdersAPI
                                    .postReplenish(params)
                                    .then((res) => {
                                        if (res?.isSucceed == false) {
                                            $.toptip(res?.msg, 'warning');
                                            return;
                                        } else {
                                            $.toptip(res?.msg, 'success');
                                            window.history.go(-1);
                                        }
                                        //location.href = `./saleorders.html?v=${Utils.GetTime()} `;
                                    })
                                    .catch((error) => {
                                        console.error(error);
                                    });
                            }
                        })
                        .catch((error) => {
                            $.toptip(error?.responseJSON?.msg, 'warning');
                            return;
                        });
                } else {
                    // 非妊娠母猪时，直接完成订单
                    saleOrdersAPI
                        .postReplenish(params)
                        .then((res) => {
                            if (res?.isSucceed == false) {
                                $.toptip(res?.msg, 'warning');
                                return;
                            } else {
                                $.toptip(res?.msg, 'success');
                                window.history.go(-1);
                            }
                            //location.href = `./saleorders.html?v=${Utils.GetTime()} `;
                        })
                        .catch((error) => {
                            $.toptip(error?.responseJSON?.msg, 'warning');
                            return;
                        });
                }
            } else {
                params['price'] = 0;
                params['totalPrice'] = 0;
                saleOrdersAPI
                    .postReplenish(params)
                    .then((res) => {
                        if (res?.isSucceed == false) {
                            $.toptip(res?.msg, 'warning');
                            return;
                        } else {
                            $.toptip(res?.msg, 'success');
                            window.history.go(-1);
                        }
                        //location.href = `./saleorders.html?v=${Utils.GetTime()} `;
                    })
                    .catch((error) => {
                        $.toptip(error?.responseJSON?.msg, 'warning');
                        return;
                    });
            }
        });
        //取消
        $('#returnMain').on('click', function () {
            window.history.go(-1);
        });
    };

    // 初始化耳号
    const _initPigInfo = async () => {
        $('#saleParity').on('input propertychange', function () {
            (checkEmploy = []), (earNumsList = []), (checkboxList = []);
            $('#choose').html(`<span style = "margin-right: 24px;">已选择:0条</span>`);
        });

        // 点击耳号 显示选择页面
        $(document).on('click', '#pigEarDiv', async function () {
            // 种猪需要先输入胎次
            if (!Utils.IsNotNull($('#saleParity').val()) && (_json.pigType == 2 || _json.pigType == 6)) {
                $.toptip('请先输入胎次！');
                return;
            }

            $('#content').empty();
            refreshQuery();
            $('#report-contact').popup();
        });
        //TODO : 耳号上拉加载
        $('#iscroll')
            .infinite()
            .on('infinite', function () {
                let _data = _vm._data.page;
                if (_data.pageIndex == _data.totalPages) return;
                let self = this;
                if (self.loading) return;
                self.loading = true;
                setTimeout(async function () {
                    queryearNumsList();
                    self.loading = false;
                }, 500); //模拟延迟
            });
        // 搜索
        $('#searchdiv form')
            .submit(function () {
                _mainSearch();
                return false;
            })
            .on('input propertychange', Utils.throttle(_mainSearch, 2000));
        search();

        // 选择耳号 复选框
        $(document).on('click', '#iscroll .weui-check__label', function (event) {
            // event.stopPropagation();   //表示阻止向父元素冒泡
            event.preventDefault(); //阻止 方法阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked');
            $(this).find("input[type='checkbox']").prop('checked', !isChecked);
            if (!isChecked == true && checkboxList.includes($(this).data('id')) == false) {
                checkboxList.push($(this).data('id'));
            } else {
                checkboxList.splice(checkboxList.indexOf($(this).data('id')), 1);
            }
            $('#subPigNumears').text(`确定(${checkboxList.length})`);
            $('#choose').html(`<span style = "margin-right: 24px;">已选择:${checkboxList.length}条</span>`);
        });

        // 取消按钮
        $('#cancelSub').on('click', function () {
            let checkHistory =
                [
                    ...checkEmploy.map((item) => {
                        return item.id;
                    }),
                ] || []; // 点取消时的上一次数据
            checkboxList = checkHistory; // 上一次点 确定的数据  赋值给  选中的数据
            $('#subPigNumears').text(`确定(${checkboxList.length})`);
            $('#choose').html(`<span style = "margin-right: 24px;"> 已选择: ${checkboxList.length}条</span> `);
            $.closePopup();
            $('#searchInput').val('');
            $('#searchBar').removeClass('weui-search-bar_focusing');
        });

        // 确定
        $('#subPigNumears').on('click', function () {
            let subData =
                [
                    ...checkboxList.map((item) => {
                        return [...earNumsList, ...checkEmploy].find((item1) => item1.id == item);
                    }),
                ] || [];
            checkEmploy = subData;
            $('#searchInput').val('');
            if (Utils.IsNotNull(checkEmploy.length)) {
                $('#choose').html(`<span style = "margin-right: 24px;"> 已选择: ${checkEmploy.length} 个</span > `);
            } else {
                $('#choose').html(`<span style = "margin-right: 24px;"> 已选择: 0 个</span > `);
            }
            $.closePopup();
            $('#searchBar').removeClass('weui-search-bar_focusing');
        });
    };

    // 计算周次
    const _weeksCalculation = (Day) => {
        /* yyyy-MM-dd格式 */
        // 创建一个目标日期对象
        let date = new Date(new Date(Day).getFullYear(), new Date(Day).getMonth(), new Date(Day).getDate());

        // 获取当年1月1日
        let yearStart = new Date(date.getFullYear(), 0, 1);
        let dayOfWeek = yearStart.getDay(); // 获取当年1月1日的星期几

        // 计算该年内的第一个周日
        let firstSunday = new Date(yearStart);
        if (dayOfWeek !== 0) {
            firstSunday.setDate(yearStart.getDate() + (7 - dayOfWeek)); // 找到该年内第一个周日
        }

        // 计算从第一个周日到目标日期的天数差，并转换为周次
        let dayDiff = (date - firstSunday) / 86400000; // 计算天数差
        let weekNo = Math.ceil((dayDiff + 1) / 7) + 1; // 转换为周次
        return weekNo;
    };
    //查询耳号信息
    const refreshQuery = async () => {
        let _page = {
            search: $('#searchInput').val(),
            breedBatchId: getWeighInfo[0]?.breedBatchId,
            pigStatus: [],
            pageIndex: 0,
            totalPages: -1,
            pageSize: 50,
            parity: $('#saleParity').val(),
        };
        _vm.page = Object.assign(_vm.page, _page);
        queryearNumsList();
    };

    function unique(arr) {
        const res = new Map();
        return JSON.parse(JSON.stringify(arr)).filter((a) => !res.has(a.id) && res.set(a.id, 1));
    }

    // 耳号 输入框
    const _mainSearch = async function () {
        let _page = {
            search: $('#searchInput').val(),
            breedBatchId: getWeighInfo[0]?.breedBatchId,
            pigStatus: [],
            pageIndex: 0,
            totalPages: -1,
            pageSize: 50,
            status: true,
            parity: $('#saleParity').val(),
        };
        _vm._data.page = Object.assign(_vm._data.page, _page);
        $('#content').empty();
        queryearNumsList();
    };
    // 耳号 输入框
    const search = () => {
        let $searchBar = $('#searchBar'),
            $searchResult = $('#searchResult'),
            $searchText = $('#searchText'),
            $searchInput = $('#searchInput'),
            $searchClear = $('#searchClear'),
            $searchForm = $('#searchForm'),
            $searchCancel = $('#searchCancel');

        function hideSearchResult() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearch() {
            hideSearchResult();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearch();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $('#content').empty();
                    //refreshQuery();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResult();
            $searchInput.focus();
            $('#content').empty();
            refreshQuery();
        });
        $searchCancel.on('click', function () {
            cancelSearch();
            $('#content').empty();
            refreshQuery();
            $searchInput.blur();
        });
    };
    //耳号 数据源
    const queryearNumsList = () => {
        let _data = _vm.page;
        let _list = [];
        saleOrdersAPI
            .postPigdocsList(
                Object.assign(
                    {
                        breedBatchId: getWeighInfo[0]?.breedBatchId,
                        pigStatus: [],
                        parity: $('#saleParity').val(),
                        eType: 7,
                        sort: 'bizFormObj.createTime desc',
                    },
                    _data,
                ),
            )
            .then((res) => {
                let _page = {
                    search: $('#searchInput').val(),
                    breedBatchId: getWeighInfo[0]?.breedBatchId,
                    pigStatus: [],
                    pageSize: 50,
                    pageIndex: _data.pageIndex + 1,
                    totalPages: res.totalPages,
                };
                _vm._data.page = Object.assign({}, _page);
                if (!Utils.IsNotNull($('#searchInput').val()) && _data.pageIndex == 0) {
                    _list.push(...checkEmploy);
                }
                _list.push(...res.items);
                unique(_list).map((item) => {
                    let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                    <div class="weui-cell__hd">
                        <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                        <i class="weui-icon-checked"></i>
                    </div>
                    <div class="" aria-hidden="true">
                        <span>耳号：${item.earNum}</span>
                        <div>耳刺：${item.earTag}</div>
                        <div>胎次：${item.parity}</div>
                    </div>
                    </div>
                </label>`;
                    $('#content').append(labhtml);
                });
                checkboxList.map((item1) => $(`#${item1}`).prop('checked', true));
                earNumsList = [...earNumsList, ...res.items];
            });
    };

    // 初始化TMS 车牌号
    const _initTmsInfo = async () => {
        // 点击车牌号 显示选择页面
        $(document).on('click', '#carNo', async function () {
            $('#contentTms').empty();
            refreshQueryTms();
            $('#report-contactTms').popup();
        });
        //TODO : 车牌号上拉加载
        $('#iscrollTms')
            .infinite()
            .on('infinite', function () {
                let _data = _vm._data.page;
                if (_data.pageIndex == _data.totalPages) return;
                let self = this;
                if (self.loading) return;
                self.loading = true;
                setTimeout(async function () {
                    queryearNumsListTms();
                    self.loading = false;
                }, 500); //模拟延迟
            });
        // 搜索
        $('#searchdivTms form')
            .submit(function () {
                _mainSearchTms();
                return false;
            })
            .on('input propertychange', Utils.throttle(_mainSearch, 2000));
        searchTms();

        // 选择车牌号 复选框
        $(document).on('click', '#iscrollTms .weui-check__label', function (event) {
            // event.stopPropagation();   //表示阻止向父元素冒泡
            event.preventDefault(); //阻止 方法阻止元素发生默认的行为（例如，当点击提交按钮时阻止对表单的提交或者a标签）
            let isChecked = $(this).find("input[type='checkbox']").is(':checked');
            $(this).find("input[type='checkbox']").prop('checked', !isChecked);
            if (!isChecked == true && checkboxListTms.includes($(this).data('id')) == false) {
                checkboxListTms.push($(this).data('id'));
            } else {
                checkboxListTms.splice(checkboxListTms.indexOf($(this).data('id')), 1);
            }
            $('#subPigNumearsTms').text(`确定(${checkboxListTms.length})`);
            $('#chooseTms').html(`<span style = "margin-right: 24px;">已选择:${checkboxListTms.length}条</span>`);
        });

        // 取消按钮
        $('#cancelSubTms').on('click', function () {
            let checkHistory =
                [
                    ...checkEmployTms.map((item) => {
                        return item.id;
                    }),
                ] || []; // 点取消时的上一次数据
            checkboxListTms = checkHistory; // 上一次点 确定的数据  赋值给  选中的数据
            $('#subPigNumearsTms').text(`确定(${checkboxListTms.length})`);
            $('#chooseTms').html(`<span style = "margin-right: 24px;"> 已选择: ${checkboxListTms.length}条</span> `);
            $.closePopup();
            $('#searchInputTms').val('');
            $('#searchBarTms').removeClass('weui-search-bar_focusing');
        });

        // 确定
        $('#subPigNumearsTms').on('click', function () {
            let subData =
                [
                    ...checkboxListTms.map((item) => {
                        return [...earNumsListTms, ...checkEmployTms].find((item1) => item1.id == item);
                    }),
                ] || [];
            checkEmployTms = subData;
            $('#searchInputTms').val('');

            if (checkEmployTms.length != 1) {
                return $.toptip(`请选择一条数据!`, 'warning');
            }
            if (Utils.IsNotNull(checkEmployTms.length)) {
                $('#chooseTms').html(`<span style = "margin-right: 24px;"> 已选择: ${checkEmployTms.length} 个</span > `);
            } else {
                $('#chooseTms').html(`<span style = "margin-right: 24px;"> 已选择: 0 个</span > `);
            }
            $('#carNo').val(checkEmployTms[0].carno);
            $('#carNoText').val(checkEmployTms[0].carno);
            $('#transferCarNo').text(checkEmployTms[0].carnO2);
            $('#deiverName').text(checkEmployTms[0].dname);
            $('#deiverPhone').text(checkEmployTms[0].dphone);
            $('#waybillNo').text(checkEmployTms[0].waybillNo);
            $('#sadress').text(checkEmployTms[0].sadress);
            $('#radress').text(checkEmployTms[0].radress);

            $.closePopup();
            $('#searchBarTms').removeClass('weui-search-bar_focusing');
        });
    };

    //查询车牌号
    const refreshQueryTms = async () => {
        let _page = {
            billNo: $('#billNo').val(),
            sort: 'bizFormObj.createTime desc',
            pageIndex: 0,
            totalPages: -1,
            pageSize: 50,
        };
        _vm.page = Object.assign(_vm.page, _page);
        queryearNumsListTms();
    };
    // 车牌号 输入框
    const _mainSearchTms = async function () {
        let _page = {
            billNo: $('#billNo').val(),
            sort: 'bizFormObj.createTime desc',
            pageIndex: 0,
            totalPages: -1,
            pageSize: 50,
            status: true,
        };
        _vm._data.page = Object.assign(_vm._data.page, _page);
        $('#contentTms').empty();
        queryearNumsListTms();
    };
    // 车牌号 输入框
    const searchTms = () => {
        let $searchBar = $('#searchBarTms'),
            $searchResult = $('#searchResultTms'),
            $searchText = $('#searchTextTms'),
            $searchInput = $('#searchInputTms'),
            $searchClear = $('#searchClearTms'),
            $searchForm = $('#searchFormTms'),
            $searchCancel = $('#searchCancelTms');

        function hideSearchResultTms() {
            $searchResult.hide();
            $searchForm.attr('aria-expanded', 'false');
            $searchInput.val('');
        }
        function cancelSearchTms() {
            hideSearchResultTms();
            $searchBar.removeClass('weui-search-bar_focusing');
            $searchText.show();
        }

        $searchText.on('click', function () {
            $searchBar.addClass('weui-search-bar_focusing');
            $searchInput.focus();
        });

        $searchInput
            .on('blur', function () {
                if (!this.value.length) cancelSearchTms();
            })
            .on('input', function () {
                if (this.value.length) {
                    $searchResult.show();
                    $searchForm.attr('aria-expanded', 'true');
                } else {
                    $('#contentTms').empty();
                    //refreshQuery();
                    $searchResult.hide();
                    $searchForm.attr('aria-expanded', 'false');
                }
            });
        $searchClear.on('click', function () {
            hideSearchResultTms();
            $searchInput.focus();
            $('#contentTms').empty();
            refreshQuery();
        });
        $searchCancel.on('click', function () {
            cancelSearchTms();
            $('#contentTms').empty();
            refreshQueryTms();
            $searchInput.blur();
        });
    };
    // 车牌号 数据源
    const queryearNumsListTms = () => {
        let _data = _vm.page;
        let _list = [];
        saleOrdersAPI
            .getTmsordersList(
                Object.assign(
                    {
                        billNo: $('#billNo').val(),
                        sort: 'bizFormObj.createTime desc',
                    },
                    _data,
                ),
            )
            .then((res) => {
                let _page = {
                    billNo: $('#billNo').val(),
                    sort: 'bizFormObj.createTime desc',
                    pageSize: 50,
                    pageIndex: _data.pageIndex + 1,
                    totalPages: res.totalPages,
                };
                _vm._data.page = Object.assign({}, _page);
                if (!Utils.IsNotNull($('#searchInputTms').val()) && _data.pageIndex == 0) {
                    _list.push(...checkEmployTms);
                }
                _list.push(...res);
                unique(_list).map((item) => {
                    let labhtml = `<label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}">
                        <div class="weui-cell__hd">
                            <input type="checkbox" class="weui-check" name="checkbox1" id="${item.id}">
                            <i class="weui-icon-checked"></i>
                        </div>
                        <div class="" aria-hidden="true">
                            <span>运输车牌：${item.carno}</span>
                            <div>司机姓名：${item.dname}</div>
                            <div>司机电话号码：${item.dphone}</div>
                            <div>中转车牌：${item.carnO2}</div>
                        </div>
                    </label>`;
                    $('#contentTms').append(labhtml);
                });
                checkboxListTms.map((item1) => $(`#${item1}`).prop('checked', true));
                earNumsListTms = [...earNumsListTms, ...res];
            });
    };
    //TODO : 附件上传
    //create周润玉
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (['image/jpg', 'image/jpeg', 'image/png'].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                if (file != false && file != undefined) {
                    formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, file);
                }
                //确认提交
                $('.weui-dialog__btn').on('click', function () {
                    if ($(this)[0].innerHTML == '确认') {
                        $.showLoading('上传中...');
                        let fileName = sliceFileName(upFiles);
                        let newfile = publicFileDraw(fileName, _vm);
                        if (newfile != false && newfile != undefined) {
                            formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            _uploadFileDraw(formFile, upFiles, _vm, newfile);
                        }
                    }
                });
                return true;
            },
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter((item) => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $('.weui-uploader__input-box').hide();
                            } else {
                                $('.weui-uploader__input-box').show();
                            }
                        },
                        onCancel: function () {},
                    });
                },
            });
        });
    };
    /**
     *@file 附件上传
     *@create周润玉
     */
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile)
            .then((res) => {
                if (res.isSucceed) {
                    let _list = _vm.images;
                    _list.push({
                        id: $('#uploaderFiles li').length,
                        imageId: res.data,
                        url: upFiles.url,
                        name: newName,
                    });
                    _vm.images = _list;
                    $('#uploaderFiles li').each(function (i) {
                        $(this).attr('data-id', _vm.images[i].id);
                        $(this).attr('data-image-id', _vm.images[i].imageId);
                        $(this).attr('data-name', _vm.images[i].name);
                        $(this).attr('data-suffix', _vm.images[i].type);
                        $(this).attr('data-url', _vm.images[i].url);
                        $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                    });
                    $('.weui-uploader__file-content').hide();
                    $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                    $.hideLoading();
                    $.closeModal();
                }
            })
            .catch((res) => {
                $('#uploaderFiles li')
                    .eq($('#uploaderFiles li').length - 1)
                    .remove();
                _vm.uploadCount = --_vm.uploadCount;
                $.toptip(res.msg, 'error');
            })
            .finally((_) => {
                $.hideLoading();
                $.closeModal();
            });
    };

    //TODO : 附件信息回显
    //Date :2022-02-16 10:19:26
    //create周润玉
    const _images = async (file) => {
        let _imag = file.split(',');
        if (_imag) {
            if (!uploader) {
                await uploadInit();
            }
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then((_res) => {
                    _vm.images.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i],
                    });
                    if (_res.isSucceed) {
                        let _li;
                        if (['jpg', 'jpeg', 'png', 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        }
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $('.weui-uploader__input-box').hide();
            }
            _vm.uploadCount = _sun;
        }
    };
})(window, document, jQuery);
